package com.tmtc.controller.appAPI;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pingplusplus.Pingpp;
import com.pingplusplus.model.Charge;
import com.tmtc.constant.MessageVar;
import com.tmtc.constant.ParameterConstant;
import com.tmtc.filter.FilterUtil;
import com.tmtc.frame.ServiceException;
import com.tmtc.po.MoneyOrder;
import com.tmtc.po.MoneyOrderRepository;
import com.tmtc.po.MoneyOrderRepository.Criteria;
import com.tmtc.service.ReChargeService;
import com.tmtc.utils.IP;
import com.tmtc.utils.IdWorker;
import com.tmtc.utils.OrderNumUtil;
import com.tmtc.utils.VerificationUtil;
import com.tmtc.utils.pingpp.ChargeExample;
import com.tmtc.utils.secret.SRSACoder;
import com.tmtc.vo.recharge.RechargeOrderVo;
import com.tmtc.vo.recharge.RechargePP;

@Controller
@RequestMapping("/App/Recharge")
public class ReChargeAppController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(ReChargeAppController.class);

	@Autowired
	ReChargeService reChargeService;

	/**
	 * 查询充值流水，包括消费 url：/App/Recharge/query？ 不用RSA加密，只用enc验证和必须是登录状态
	 * @param request
	 * @param page
	 * @param rows
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(HttpServletRequest request,@RequestParam(required = true) Integer page,
			@RequestParam(required = true) Integer rows) {
		String userId = getUserId(request);
		List<MoneyOrder> list = reChargeService.findMoneyOrder(userId,page, rows);
		return getMap(request, "",list);
	}

	/**
	 * 充值下单 url ： /App/Recharge/order？
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/order")
	public Map<String, Object> order(HttpServletRequest request, HttpServletResponse response) {
		try {
			String data = (String) request.getAttribute("data");
			RechargeOrderVo rechargeOrderVo = new Gson().fromJson(data, new TypeToken<RechargeOrderVo>() {
			}.getType());
			if (null == rechargeOrderVo) {
				return getMap(request, MessageVar.RECHARGE_ERROR, STATUS_ERROR);
			}

			String card_no = rechargeOrderVo.getCard_no();
			int money = rechargeOrderVo.getMoney();
			if (0 == VerificationUtil.length(card_no) || 0 == VerificationUtil.integerIsNull(money)) {
				return getMap(request, MessageVar.RECHARGE_ERROR, STATUS_ERROR);
			}

			Map<String, Object> _params = new TreeMap<String, Object>();
			_params.put("card_no", card_no);
			_params.put("money", money);
			_params.put("timekey", rechargeOrderVo.getTimeKey());
			boolean b = FilterUtil.verifiy(_params, rechargeOrderVo.getEnc(), request, response);
			if (!b) {
				return null;
			}

			String orderByCZ = OrderNumUtil.getOrderByCZ();
			MoneyOrder moneyOrder = new MoneyOrder(IdWorker.nextId(), getUserId(request), card_no, orderByCZ, money,
					null, ParameterConstant.CZ_ORDER_STATUS_NULL, new Date());
			int i = reChargeService.insert(moneyOrder);
			if (i > 0) {
				logger.info("充值下单成功，订单号:" + orderByCZ + "金额为：" + money);
				return getMap(request, MessageVar.RECHARGE_SUCCESS, SRSACoder.sign(moneyOrder));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return getMap(request, MessageVar.RECHARGE_ERROR, STATUS_ERROR);
		}
		return getMap(request, MessageVar.RECHARGE_ERROR, STATUS_ERROR);
	}

	/**
	 * ping++充值 /App/Recharge/pp
	 * 
	 * @param request
	 * @param order_no
	 *            订单号
	 * @param channel
	 *            充值类型
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/pp")
	public Map<String, Object> pingPP(HttpServletRequest request, HttpServletResponse response) {
		try {
			String data = (String) request.getAttribute("data");
			RechargePP rechargePP = new Gson().fromJson(data, new TypeToken<RechargePP>() {
			}.getType());
			if (null == rechargePP) {
				return getMap(request, MessageVar.RECHARGE_ERROR, STATUS_ERROR);
			}

			String order_no = rechargePP.getOrder_no();
			String channel = rechargePP.getChannel();
			if (0 == VerificationUtil.length(order_no) || 0 == VerificationUtil.length(channel)
					|| 19 != VerificationUtil.length(order_no) || !(channel.equals("alipay") || channel.equals("wx"))) {
				return getMap(request, MessageVar.RECHARGE_ERROR, STATUS_ERROR);
			}

			Map<String, Object> _params = new TreeMap<String, Object>();
			_params.put("order_no", order_no);
			_params.put("channel", channel);
			_params.put("timekey", rechargePP.getTimeKey());
			boolean b = FilterUtil.verifiy(_params, rechargePP.getEnc(), request, response);
			if (!b) {
				return null;
			}

			MoneyOrderRepository moneyOrderRepository = new MoneyOrderRepository();
			Criteria criteria = moneyOrderRepository.createCriteria();
			criteria.andOrder_noEqualTo(order_no);

			List<MoneyOrder> list = reChargeService.select(moneyOrderRepository);
			if (0 == VerificationUtil.size(list)) {
				return getMap(request, "订单不存在", STATUS_ERROR);
			}
			MoneyOrder moneyOrder2 = list.get(0);
			Integer status = moneyOrder2.getOrder_status();

			switch (status) {
			case ParameterConstant.CZ_ORDER_STATUS_NULL:
				break;
			case ParameterConstant.CZ_ORDER_STATUS_FINISH:
				return getMap(request, "该订单已经付过款", STATUS_ERROR);
			case ParameterConstant.CZ_ORDER_STATUS_OVER:
				return getMap(request, "该订单已经过期", STATUS_ERROR);
			default:
				break;
			}
			Pingpp.apiKey = ParameterConstant.apiKey;
			Charge charge = ChargeExample.charge(moneyOrder2.getMoney(), order_no, IP.getIP(request), channel);
			logger.info(charge.toString());
			return getMap(request, "请求充值成功", charge.toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("#######################充值失败##################");
			return getMap(request, "充值失败,请重新下单再次充值", STATUS_ERROR);
		}
	}

	/**
	 * /App/Recharge/findCharge 确认充值
	 *
	 * @param request
	 * @param charge
	 *            Charge类型的字符串
	 * @return
	 * @throws ServiceException
	 */
	@ResponseBody
	@RequestMapping("/findCharge")
	public Map<String, Object> findCCharge(HttpServletRequest request, HttpServletResponse response, String charge)
			throws ServiceException {
		
		MoneyOrder moneyOrder = null;
		try {
			Charge charge1 = new Gson().fromJson(charge, new TypeToken<Charge>() {}.getType());
			if (null == charge1) {
				return getMap(request, "充值错误", STATUS_ERROR);
			}
			Pingpp.apiKey = ParameterConstant.apiKey;
			Charge charge2 = ChargeExample.retrieve(charge1.getId());
			if (null == charge2) {
				return getMap(request, "充值失败,请重新下单再次充值", STATUS_ERROR);
			}
			if (!charge2.getPaid()) {
				return getMap(request, "您还未充值！！", STATUS_ERROR);
			}

			logger.info(charge2.toString());

			MoneyOrderRepository moneyOrderRepository = new MoneyOrderRepository();
			Criteria criteria = moneyOrderRepository.createCriteria();
			criteria.andOrder_noEqualTo(charge2.getOrderNo());
			List<MoneyOrder> list = reChargeService.select(moneyOrderRepository);
			if (0 == list.size()) {
				return getMap(request, "充值错误", STATUS_ERROR);
			}
			moneyOrder = list.get(0);
			if (ParameterConstant.CZ_ORDER_STATUS_FINISH == moneyOrder.getOrder_status()) {
				return getMap(request, "充值成功");
			}

			String channel = charge2.getChannel();
			if (channel.equals("wx")) {
				moneyOrder.setPay_type(ParameterConstant.PAY_TYPE_ALIPAY);
			} else if (channel.equals("alipay")) {
				moneyOrder.setPay_type(ParameterConstant.PAY_TYPE_WECHAR);
			}
			moneyOrder.setOrder_status(ParameterConstant.CZ_ORDER_STATUS_FINISH);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("#######################充值失败##################");
			return getMap(request, "充值失败,请重新下单再次充值", STATUS_ERROR);
		}
		reChargeService.updatereCharger(moneyOrder);
		return getMap(request, "充值成功");
	}
}
